import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-16
 * Time: 11:00
 */
class MyThreadPool{

    BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(100);
    ArrayList<Thread> arrayList=new ArrayList<>();
    public int max=0;
    public MyThreadPool(int capacity,int max){
        this.max= max;
        for (int i = 0; i <capacity ; i++) {
            Thread t=new Thread(()->{
                try{
                    while(true){
                        Runnable runnable=queue.take();
                        runnable.run();
                    }

                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            });
            t.start();
            arrayList.add(t);
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        if(queue.size()>=100&&arrayList.size()<=max){
            Thread t =new Thread(()->{
                Runnable runnable1= null;
                try {
                    while(true){
                        runnable1 = queue.take();
                        runnable1.run();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            });
            t.start();
            arrayList.add(t);
        }
        queue.put(runnable);
    }
}
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool=new MyThreadPool(10,15);//
        for (int i = 0; i <10000 ; i++) {//10000个任务
            int id=i;
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello "+id +", "+Thread.currentThread().getName());
                }

            });
        }
    }
}
